/* eslint-disable no-param-reassign */
import { defineComponent, ref } from 'vue';
import {
  getEditorEmits,
  getUploadProps,
  useFocusAndBlur,
  useNamespace,
} from '@ibiz-template/vue3-util';
import { CrmImageUploadController } from './crm-image-upload.controller';
import { useIViewUpload } from './use/use-iview-upload';
import { resource } from '../global';
import './crm-image-upload.scss';

export const CrmImageUpload = defineComponent({
  name: 'CrmImageUpload',
  props: getUploadProps<CrmImageUploadController>(),
  emits: getEditorEmits(),
  setup(props, { emit }) {
    const ns = useNamespace('crm-image-upload');

    const c = props.controller;

    const {
      uploadUrl,
      headers,
      files,
      limit,
      onDownload,
      onError,
      onRemove,
      onSuccess,
      beforeUpload,
    } = useIViewUpload(
      props,
      value => {
        emit('change', value);
      },
      c,
    );

    const dialogImageUrl = ref<string>('');
    const dialogVisible = ref<boolean>(false);

    const onDialogVisibleChange = (value: boolean) => {
      dialogVisible.value = value;
    };

    // 预览
    const onPreview = (file: IData) => {
      dialogImageUrl.value = file.url;
      dialogVisible.value = true;
    };

    // 聚焦失焦事件
    const { componentRef } = useFocusAndBlur(
      () => emit('focus'),
      () => emit('blur'),
    );

    const isShowDialog = ref(false);

    const onUploadSuccess = (response: IData) => {
      onSuccess(response);
      isShowDialog.value = false;
    };

    const onDropdownClick = async (command: string, file: IData) => {
      if (command === 'preview') {
        onPreview(file);
      }
      if (command === 'upload') {
        isShowDialog.value = true;
      }
      if (command === 'delete') {
        const result = await ibiz.confirm.info({ title: '您确定要移除吗？' });
        if (result) {
          onRemove(file);
        }
      }
    };

    return {
      ns,
      c,
      files,
      limit,
      headers,
      uploadUrl,
      dialogImageUrl,
      dialogVisible,
      beforeUpload,
      onSuccess,
      onUploadSuccess,
      onError,
      onRemove,
      onDownload,
      onDialogVisibleChange,
      onPreview,
      componentRef,
      isShowDialog,
      onDropdownClick,
    };
  },
  render() {
    return (
      <div class={[this.ns.b()]} ref='componentRef'>
        <div class={this.ns.b('list')}>
          {this.files.length ? (
            this.files.map(item => (
              <el-dropdown
                trigger='click'
                onCommand={(command: string) =>
                  this.onDropdownClick(command, item)
                }
              >
                {{
                  default: () => {
                    return (
                      <div key={item.id} class={this.ns.b('list-item')}>
                        <img src={item.url} />
                        <div class={this.ns.b('list-item-cover')}>
                          <div
                            class={this.ns.b('list-item-camera-icon')}
                            style={{
                              backgroundImage: `url(${resource.dir(
                                './assets/svg/svg.svg',
                              )})`,
                            }}
                          ></div>
                        </div>
                      </div>
                    );
                  },
                  dropdown: () => {
                    return (
                      <el-dropdown-menu>
                        <el-dropdown-item command='preview'>
                          预览图片
                        </el-dropdown-item>
                        <el-dropdown-item command='upload'>
                          上传图片
                        </el-dropdown-item>
                        <el-dropdown-item command='delete' divided={true}>
                          删除
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    );
                  },
                }}
              </el-dropdown>
            ))
          ) : (
            <div class={this.ns.b('list-item')}>
              <img src={resource.dir('./assets/svg/company.svg')} />
              <div
                class={this.ns.b('list-item-cover')}
                onClick={() => {
                  this.isShowDialog = true;
                }}
              >
                <div
                  class={this.ns.b('list-item-camera-icon')}
                  style={{
                    backgroundImage: `url(${resource.dir(
                      './assets/svg/svg.svg',
                    )})`,
                  }}
                ></div>
              </div>
            </div>
          )}
        </div>
        {this.dialogVisible ? (
          <el-image-viewer
            onClose={() => this.onDialogVisibleChange(false)}
            url-list={[this.dialogImageUrl]}
            hide-on-click-modal={true}
            close-on-press-escape={true}
            teleported
            z-index={9999}
            {...this.$attrs}
          ></el-image-viewer>
        ) : null}
        <el-dialog
          class={this.ns.b('dialog')}
          v-model={this.isShowDialog}
          title='选择照片'
          width='900'
        >
          {{
            default: () => {
              return (
                <div class={this.ns.b('dialog-content')}>
                  <div class={this.ns.be('dialog-content', 'tip')}>
                    在这里选择您的照片
                  </div>
                  <el-upload
                    file-list={[]}
                    action={this.uploadUrl}
                    headers={this.headers}
                    disabled={this.disabled}
                    multiple={this.c.multiple}
                    limit={this.limit}
                    show-file-list={false}
                    accept={this.c.accept}
                    before-upload={this.beforeUpload}
                    onSuccess={this.onUploadSuccess}
                    onError={this.onError}
                    onRemove={this.onRemove}
                    onPreview={this.onDownload}
                    {...this.$attrs}
                  >
                    {{
                      trigger: () => {
                        return <el-button>浏览本地文件</el-button>;
                      },
                    }}
                  </el-upload>
                </div>
              );
            },
          }}
        </el-dialog>
      </div>
    );
  },
});
